package com.enation.app.javashop.core.payment.plugin.walletpay.executor;

import com.dag.eagleshop.core.account.model.dto.payment.UnfreezeConfirmPayReqDTO;
import com.dag.eagleshop.core.account.model.dto.payment.UnfreezeConfirmPayRespDTO;
import com.dag.eagleshop.core.account.model.enums.AccountTypeEnum;
import com.dag.eagleshop.core.account.service.AccountPaymentManager;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.payment.model.vo.Form;
import com.enation.app.javashop.core.payment.model.vo.FormItem;
import com.enation.app.javashop.core.payment.model.vo.PayBill;
import com.enation.app.javashop.core.payment.service.PaymentBillManager;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.core.trade.sdk.model.OrderDetailDTO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author 王志杨
 * @since 2020/10/15 15:37
 * 钱包支付执行器
 */
@Service
public class WalletPaymentExecutor {

    @Autowired
    private AccountPaymentManager accountPaymentManager;

    @Autowired
    private PaymentBillManager paymentBillManager;

    @Autowired
    private MemberManager memberManager;

    @Autowired
    private OrderQueryManager orderQueryManager;

    private final Log logger = LogFactory.getLog(getClass());

    /**
     * 账户解冻并确认支付--冻结在订单创建消费者中AccountFreezeConsumer
     */
    public Form pay(PayBill bill) {
        try {
            //拼装请求参数
            logger.debug("开始准备调用账户解冻并确认支付接口参数");

            //查询购买的商品，获取买家
            OrderDetailDTO orderDetail = orderQueryManager.getModel(bill.getSn());
            Member member = memberManager.getModel(orderDetail.getMemberId());
            UnfreezeConfirmPayReqDTO unfreezeConfirmPayReqDTO = this.buildUnfreezeConfirmPayReqDTO(bill, member);

            logger.debug("调用账户解冻并确认支付接口参数准备完成，请求参数：" + unfreezeConfirmPayReqDTO);

            logger.debug("开始调用账户解冻并确认支付接口");
            UnfreezeConfirmPayRespDTO unfreezeConfirmPayRespDTO = accountPaymentManager.unfreezeConfirmPay(unfreezeConfirmPayReqDTO);
            logger.debug("结束调用账户解冻并确认支付接口，支付返回结果：" + unfreezeConfirmPayRespDTO);
            boolean isSuccess = unfreezeConfirmPayRespDTO.isSuccess();
            Form form = new Form();
            if (isSuccess) {
                //支付成功，调用paySuccess
                logger.debug("账户解冻并确认支付成功，开始修改支付账单和订单状态，并发送订单状态改变消息");
                String serialNo = unfreezeConfirmPayRespDTO.getSerialNo();
                double payPrice = unfreezeConfirmPayRespDTO.getAmount().doubleValue();
                paymentBillManager.paySuccess(bill.getBillSn(), serialNo, bill.getTradeType(), payPrice);

                //组装返回值
                Map<String, String> result = new TreeMap<>();
                result.put("seriaNo", serialNo);
                result.put("amount", payPrice + "");
                result.put("tradeVoucherNo", unfreezeConfirmPayRespDTO.getTradeVoucherNo());
                result.put("message", unfreezeConfirmPayRespDTO.getMessage());
                result.put(Form.RESULT, Form.SUCCESS);
                result.put("paymentPluginId", bill.getPluginId());

                List<FormItem> items = new ArrayList<>();
                for (String key : result.keySet()) {
                    FormItem item = new FormItem();
                    item.setItemName(key);
                    item.setItemValue(result.get(key));
                    items.add(item);
                }
                form.setFormItems(items);
                return form;
            } else {
                this.logger.error("账户解冻并确认支付失败：" + unfreezeConfirmPayRespDTO.getMessage());
                return Form.failForm(unfreezeConfirmPayRespDTO.getMessage());
            }
        } catch (Exception e) {
            this.logger.error("账户解冻并确认支付失败：", e);
            return Form.failForm("账户解冻并确认支付：" + e.getMessage());
        }
    }


    /**
     * 查询支付结果
     */
    public String onQuery(PayBill bill) {
        return null;
    }

    //初始化一个账户解冻并确认支付请求DTO
    private UnfreezeConfirmPayReqDTO buildUnfreezeConfirmPayReqDTO(PayBill bill, Member member){

        UnfreezeConfirmPayReqDTO unfreezeConfirmPayReqDTO = new UnfreezeConfirmPayReqDTO();
        unfreezeConfirmPayReqDTO.setAccountType(AccountTypeEnum.MEMBER_MASTER.getIndex());
        unfreezeConfirmPayReqDTO.setAmount(BigDecimal.valueOf(bill.getOrderPrice()));
        unfreezeConfirmPayReqDTO.setDraweeMemberId(member.getAccountMemberId());
        unfreezeConfirmPayReqDTO.setOperatorId(member.getMemberId().toString());
        unfreezeConfirmPayReqDTO.setOperatorName(member.getNickname());
        unfreezeConfirmPayReqDTO.setTradeVoucherNo(bill.getBillSn());
        return unfreezeConfirmPayReqDTO;
    }
}
